package com.jichangxiu.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ThreadUtils {

    private static final Logger logger = LoggerFactory.getLogger(ThreadUtils.class);

    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            logger.error("【ThreadUtils】线程等待异常" + ex.getMessage());
        }
    }

    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS))
                        logger.error("【ThreadUtils】线程池未终止");
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                pool.shutdownNow();
                Thread.currentThread().interrupt();
                logger.error("【ThreadUtils】线程关闭异常" + ex.getMessage());
            }
        }
    }

    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone())
                    future.get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            t.printStackTrace();
            logger.error("【ThreadUtils】线程打印异常");
        }
    }

}
